<template>
  <div>
    <div class="search">
      <input class="city-search" type="text" placeholder="输入城市名或拼音" v-model="keyword" />
    </div>
    <div v-show="keyword" class="search-content" ref="wrapper">
      <ul>
        <li class="item border-bottom" v-for="item of keyList" :key="item.id" @click="cityChange(item.name)">
          {{item.name}}
        </li>
        <li class="item" v-show="tipShow">没有匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'CityHeader',
  props: {
    cities: Object
  },
  data: function () {
    return {
      keyword: '',
      timer: null,
      keyList: []
    }
  },
  computed: {
    tipShow: function () {
      return !this.keyList.length
    }
  },
  watch: {
    keyword: function () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const list = []
        if (!this.keyword) {
          this.keyList = []
          return
        }
        for (let i in this.cities) {
          this.cities[i].forEach((value, index) => {
            if (value.spell.indexOf(this.keyword) !== -1 || value.name.indexOf(this.keyword) !== -1) {
              list.push(value)
            }
          })
        }
        this.keyList = list
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper)
  },
  methods: {
    cityChange: function (city) {
      this.$store.dispatch('cChange', city)
      this.$router.push('/')
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    padding: 0  .1rem
    height: .72rem
    background: $bgColor
    font-size: .18rem
    .city-search
      box-sizing: border-box
      width: 100%
      height: .62rem
      line-height :.62rem
      padding:0  .1rem
      border-radius: .08rem
      text-align:center
  .search-content
    overflow:hidden
    position: absolute
    left:0
    top:1.58rem
    bottom: 0
    right: 0
    font-size: .18rem
    background: #fff
    z-index:1
    .item
      padding-left: .2rem
      height:.86rem
      line-height:.86rem
</style>
